package com.example.choupaiapp.main.activity.home;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.GsonUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.SearchHotBean;
import com.example.choupaiapp.main.bean.SearchLastestBean;
import com.example.choupaiapp.main.constant.Url;
import com.lzy.okgo.model.Response;
import com.umeng.analytics.MobclickAgent;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/11/20.
 */

public class SearchActivity extends CommonActivity {

    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.flowlayout)
    TagFlowLayout flowlayout;
    @BindView(R.id.clear)
    ImageView clear;
    @BindView(R.id.delete_search)
    ImageView delete_search;
    @BindView(R.id.gridview)
    GridView gridView;
    @BindView(R.id.lastest_search)
    LinearLayout lastest_search;
    private TagAdapter<String> tagAdapter;
    private QuickAdapter<SearchHotBean.PageBean.ListBean> quickAdapter;
    private Drawable icon_hot_search;
    private Drawable icon_new_search;
    private SearchLastestBean searchLastestBean;
    private List<String> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
    }


    private void setSoftKeyboard(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();

        //为 commentEditText 设置监听器，在 DialogFragment 绘制完后立即呼出软键盘，呼出成功后即注销
        editText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    if (inputMethodManager.showSoftInput(editText, 0)) {
                        editText.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);

        String lasetestjson = (String) SharedPreferencesHelp.get("Search_Lasetest", "");
        if (!TextUtils.isEmpty(lasetestjson)) {
            searchLastestBean = GsonUtil.jsonStringToClassWithGson(lasetestjson, SearchLastestBean.class);
        }

        icon_hot_search = getResources().getDrawable(R.mipmap.icon_hot_search);
        icon_new_search = getResources().getDrawable(R.mipmap.icon_new_search);
        // 这一步必须要做,否则不会显示.
        icon_hot_search.setBounds(0, 0, 26, 26);
        icon_new_search.setBounds(0, 0, 26, 26);

        quickAdapter = new QuickAdapter<SearchHotBean.PageBean.ListBean>(context, R.layout.hot_search) {
            @Override
            protected void convert(BaseAdapterHelper helper, SearchHotBean.PageBean.ListBean item) {
                TextView index = helper.getView(R.id.index);
                TextView content = helper.getView(R.id.content);
                content.setText(item.getName());
                index.setText((helper.getPosition() + 1) + "");
                if (helper.getPosition() == 0) {
                    index.setTextColor(Color.parseColor("#FF6161"));
                } else if (helper.getPosition() == 1) {
                    index.setTextColor(Color.parseColor("#FFA461"));
                } else if (helper.getPosition() == 2) {
                    index.setTextColor(Color.parseColor("#FFCD61"));
                } else {
                    index.setTextColor(Color.parseColor("#666666"));
                }
                if (item.getLabel() == 0) {
                    content.setCompoundDrawables(null, null, null, null);
                } else if (item.getLabel() == 1) {
                    content.setCompoundDrawables(null, null, icon_new_search, null);
                } else if (item.getLabel() == 2) {
                    content.setCompoundDrawables(null, null, icon_hot_search, null);
                } else {
                    content.setCompoundDrawables(null, null, null, null);
                }
            }
        };

        gridView.setAdapter(quickAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Bundle bundle = new Bundle();
                bundle.putString("name", quickAdapter.getItem(i).getName());
                startActivity(SearchResultActivity.class, bundle);

                if (searchLastestBean == null) {
                    searchLastestBean = new SearchLastestBean();
                    searchLastestBean.setList(new LinkedList<String>());
                }

                if (searchLastestBean.getList().size() > 0) {
                    if (searchLastestBean.getList().contains(quickAdapter.getItem(i).getName())) {
                        searchLastestBean.getList().remove(quickAdapter.getItem(i).getName());
                    }
                }

                if (searchLastestBean.getList().size() >= 10) {
                    searchLastestBean.getList().remove(searchLastestBean.getList().size() - 1);
                    searchLastestBean.getList().addFirst(quickAdapter.getItem(i).getName());
                } else {
                    searchLastestBean.getList().addFirst(quickAdapter.getItem(i).getName());
                }

                String json = GsonUtil.parseObjectToJsonString(searchLastestBean);
                SharedPreferencesHelp.put("Search_Lasetest", json);

                lastest_search.setVisibility(View.VISIBLE);
                list = searchLastestBean.getList();
                tagAdapter.notifyDataChanged();

            }
        });


        if (!TextUtils.isEmpty(lasetestjson)) {
            lastest_search.setVisibility(View.VISIBLE);
        } else {
            lastest_search.setVisibility(View.GONE);
        }

        if(searchLastestBean==null){
            searchLastestBean = new SearchLastestBean();
            searchLastestBean.setList(new LinkedList<String>());
            list = searchLastestBean.getList();
        }else{
            list = searchLastestBean.getList();
        }
        tagAdapter = new TagAdapter<String>(list) {
            @Override
            public View getView(FlowLayout parent, int position, String item) {
                View view = View.inflate(context, R.layout.item_search_tag, null);
                TextView textView = view.findViewById(R.id.textview);
                textView.setText(item);
                return view;
            }
        };
        flowlayout.setAdapter(tagAdapter);

        flowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Bundle bundle = new Bundle();
                bundle.putString("name", list.get(position));
                startActivity(SearchResultActivity.class, bundle);
                if(position!=0){
                    String s = tagAdapter.getItem(position);
                    if (searchLastestBean == null) {
                        searchLastestBean = new SearchLastestBean();
                        searchLastestBean.setList(new LinkedList<String>());
                    }

                    if (searchLastestBean.getList().size() > 0) {
                        if (searchLastestBean.getList().contains(tagAdapter.getItem(position))) {
                            searchLastestBean.getList().remove(s);
                        }
                    }

                    if (searchLastestBean.getList().size() >= 10) {
                        searchLastestBean.getList().remove(searchLastestBean.getList().size() - 1);
                        searchLastestBean.getList().addFirst(tagAdapter.getItem(position));
                    } else {
                        searchLastestBean.getList().addFirst(s);
                    }

                    String json = GsonUtil.parseObjectToJsonString(searchLastestBean);
                    SharedPreferencesHelp.put("Search_Lasetest", json);

                    lastest_search.setVisibility(View.VISIBLE);
                    list = searchLastestBean.getList();
                    tagAdapter.notifyDataChanged();
                }
                return true;
            }
        });

        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() > 0) {
                    clear.setVisibility(View.VISIBLE);
//                    //搜索内容
                    Bundle bundle = new Bundle();
                    bundle.putString("name", searchEt.getText().toString().trim());
                    startActivity(SearchResultActivity.class, bundle);
                } else {
                    clear.setVisibility(View.INVISIBLE);
                }
            }
        });

        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索的时候隐藏软键盘
                    InputMethodManager manager = (InputMethodManager) searchEt.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    manager.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
                    // 在这里写搜索的操作,一般都是网络请求数据

                    if (!TextUtils.isEmpty(searchEt.getText().toString().trim())) {
                        //搜索内容
                        Bundle bundle = new Bundle();
                        bundle.putString("name", searchEt.getText().toString().trim());
                        startActivity(SearchResultActivity.class, bundle);

                        if (searchLastestBean == null) {
                            searchLastestBean = new SearchLastestBean();
                            searchLastestBean.setList(new LinkedList<String>());
                        }

                        if (searchLastestBean.getList().size() > 0) {
                            if (searchLastestBean.getList().contains(searchEt.getText().toString().trim())) {
                                searchLastestBean.getList().remove(searchEt.getText().toString().trim());
                            }
                        }

                        if (searchLastestBean.getList().size() >= 10) {
                            searchLastestBean.getList().remove(searchLastestBean.getList().size() - 1);
                            searchLastestBean.getList().addFirst(searchEt.getText().toString().trim());
                        } else {
                            searchLastestBean.getList().addFirst(searchEt.getText().toString().trim());
                        }

                        String json = GsonUtil.parseObjectToJsonString(searchLastestBean);
                        SharedPreferencesHelp.put("Search_Lasetest", json);

                        lastest_search.setVisibility(View.VISIBLE);
                        list = searchLastestBean.getList();
                        tagAdapter.notifyDataChanged();

                    } else {
                        //搜索第一个
                        if (quickAdapter.getCount() > 0) {
                            Bundle bundle = new Bundle();
                            bundle.putString("name", quickAdapter.getItem(0).getName());
                            startActivity(SearchResultActivity.class, bundle);

                            if (searchLastestBean == null) {
                                searchLastestBean = new SearchLastestBean();
                                searchLastestBean.setList(new LinkedList<String>());
                            }

                            if (searchLastestBean.getList().size() > 0) {
                                if (searchLastestBean.getList().contains(quickAdapter.getItem(0).getName())) {
                                    searchLastestBean.getList().remove(quickAdapter.getItem(0).getName());
                                }
                            }

                            if (searchLastestBean.getList().size() >= 10) {
                                searchLastestBean.getList().remove(searchLastestBean.getList().size() - 1);
                                searchLastestBean.getList().addFirst(quickAdapter.getItem(0).getName());
                            } else {
                                searchLastestBean.getList().addFirst(quickAdapter.getItem(0).getName());
                            }

                            String json = GsonUtil.parseObjectToJsonString(searchLastestBean);
                            SharedPreferencesHelp.put("Search_Lasetest", json);

                            lastest_search.setVisibility(View.VISIBLE);
                            list = searchLastestBean.getList();
                            tagAdapter.notifyDataChanged();
                        }
                    }
                    return true;
                }

                return false;
            }
        });

        setSoftKeyboard(searchEt);
    }

    @Override
    protected void initData() {
        showDialog(context, null);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.SEARCH_HOT, null, Url.SEARCH_HOT, new Callback<SearchHotBean>() {
            @Override
            public void onSuccess(SearchHotBean searchHotBean) {
                dismissDialog();
                if (searchHotBean.getCode() == Contacts.SUCCESS) {
                    MobclickAgent.onEvent(ContextUtil.getContext(), "searchID");
                    searchEt.setHint("大家都在搜#" + searchHotBean.getPage().getList().get(0).getName() + "#");
                    quickAdapter.clear();
                    quickAdapter.addAll(searchHotBean.getPage().getList());
                    quickAdapter.notifyDataSetChanged();
                } else {
                    if (searchHotBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(searchHotBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });

    }

//    @Override
    @OnClick({R.id.clear, R.id.cancel, R.id.delete_search})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.clear:
                searchEt.setText("");
                break;
            case R.id.cancel:
                finishActivity();
                break;
            case R.id.delete_search:
                SharedPreferencesHelp.remove("Search_Lasetest");
                searchLastestBean.getList().clear();
                lastest_search.setVisibility(View.GONE);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.equals("search_lasetest_save")) {
            String lasetestjson = (String) SharedPreferencesHelp.get("Search_Lasetest", "");
            if (!TextUtils.isEmpty(lasetestjson)) {
                searchLastestBean = GsonUtil.jsonStringToClassWithGson(lasetestjson, SearchLastestBean.class);
                lastest_search.setVisibility(View.VISIBLE);
                list = searchLastestBean.getList();
                tagAdapter.notifyDataChanged();
            }
        }
    }
}
